package com.ditty.kit;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * 文件操作类
 * 
 * @author dingnate
 *
 */
public class FileKit {
	FileKit() {
	}

	/**
	 * 获取dir目录下子文件，带递归开关
	 * 
	 * @param dir
	 * @param recusive
	 * @return
	 */
	public static Collection<File> listFiles(File dir, boolean recusive) {
		return list(dir, new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.isFile();
			}
		}, recusive);
	}

	/**
	 * 获取dir目录下子文件/目录，带递归开关
	 * 
	 * @param dir
	 * @param filter 可以为null
	 * @param recusive
	 * @return
	 */
	public static Collection<File> list(File dir, FileFilter filter, boolean recusive) {
		if (!dir.exists() || !dir.isDirectory()) {
			return Collections.emptyList();
		}
		ArrayList<File> list = new ArrayList<File>();
		internalList(list, dir, filter, recusive);
		return list;
	}

	private static void internalList(Collection<File> files, File dir, FileFilter filter, boolean recusive) {
		String[] ss = dir.list();
		if (ss == null) {
			return;
		}
		for (String s : ss) {
			File f = new File(dir, s);
			boolean accept = true;
			if (filter != null) {
				accept = filter.accept(f);
			}
			if (accept && files != null) {
				files.add(f);
			}
			if (recusive && f.isDirectory()) {
				internalList(files, f, filter, recusive);
			}
		}
	}

	/**
	 * 写字节数组到文件
	 * 
	 * @param bytes
	 * @param path
	 * @throws IOException
	 */
	public static void writeToFile(byte[] bytes, String path) throws IOException {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(path);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} finally {
			IoKit.closeQuiet(bos);
			IoKit.closeQuiet(fos);
		}
	}

	/**
	 * 写字符串到文件
	 * 
	 * @param content
	 * @param path
	 * @throws IOException
	 */
	public static void writeToFile(String content, String path) throws IOException {
		writeToFile(content.getBytes(CharsetKit.DEFAULT_CHARSET), path);
	}

	/**
	 * 写字符串到文件
	 * 
	 * @param content
	 * @param path
	 * @throws IOException
	 */
	public static byte[] readFile(File file) throws IOException {
		FileInputStream fis = null;
		ByteArrayOutputStream baos = null;
		try {
			fis = new FileInputStream(file);
			baos = new ByteArrayOutputStream();
			IoKit.copy(fis, baos);
			return baos.toByteArray();
		} finally {
			IoKit.closeQuiet(fis);
			IoKit.closeQuiet(baos);
		}
	}
}
